package gitee.android.KUI.widget

import android.app.ActionBar.LayoutParams
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Point
import android.graphics.RectF
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.View
import gitee.android.KUI.MeasureText
import gitee.android.KUI.R


/**
 * @author 程序员Keven
 * 描述 : 花瓣的导航
 * 时间 : 2023-01-10
 */

class HuaBanTabBar(context: Context, attrs: AttributeSet?) :
    View(context, attrs) {

    private  var data = mutableListOf<String>();
    var   OrdX   = 0f;

    // 普通文字画笔
    private lateinit var textPaint: Paint;
    // 选中的背景画笔
    private lateinit var selectPaint : Paint;
    // 选中的 文字画笔
    private lateinit var selectTextPaint : Paint;


    /**
     * 默认高度
     */
    private var HuabanHeight = 40f;
    private var HuaBanWidth = 200f;

    /**
     * 字的大小
     */
    private var textSize = 100f;


    /**
     * 标签左右间距
     */

    private var LeftFromeRightDistance = 30f;

    /**
     * 当前选中的标签的位置索引
     */
    var index = 0;

    /**
     * 选中的文字
     */
    var selectText = "";

    /**
     * 选中的背景颜色
     */

    private var selectBackgroundColor = Color.BLACK;

    /**
     * 选中背景的半径
     */

    private var selectBackgroundr  = 10f;

    // 每一个背景起始的位置
    private var rectStartPoint  = mutableListOf<Point>();


    // 记录当前得到距离

    public var currentDistance = 0F;


    // 存储距离 用于滑动监测判断

    public var distances = mutableListOf<Float>();

    // 优化 存储距离 的性能
    private var isStart = true;


    // 右边偏移的距离
    private var offset = 0f;


    init {

        val typedArray =
            context.obtainStyledAttributes(attrs, R.styleable.HuaBanTabBar);
        textSize = typedArray.getDimension(R.styleable.HuaBanTabBar_hua_ban_text_size , 10F);
        LeftFromeRightDistance = typedArray.getDimension(R.styleable.HuaBanTabBar_Left_Right_distance , 10F);
        selectBackgroundr = typedArray.getDimension(R.styleable.HuaBanTabBar_select_bg_r , 10F);
        typedArray.recycle();


        initPaint();

    }

    private fun initPaint() {

        textPaint = Paint();
        textPaint.color = Color.BLACK;
        textPaint.textSize = textSize ;
        textPaint.strokeWidth = 1f;
        textPaint.isAntiAlias = true;

        selectTextPaint = Paint();
        selectTextPaint.color = Color.WHITE;
        selectTextPaint.textSize = textSize ;
        selectTextPaint.strokeWidth = 1f;
        selectTextPaint.isAntiAlias = true;

        selectPaint = Paint();
        selectPaint.color = Color.BLACK;
        selectPaint.strokeWidth = 1f;
        selectPaint.isAntiAlias = true;
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

        /**
         * 只允许 给定的宽高  和 warp   如果  他是 match = > warp
         */
        HuaBanWidth = layoutParams.width.toFloat()
        HuabanHeight = layoutParams.height.toFloat()

        if (layoutParams.width == LayoutParams.WRAP_CONTENT || layoutParams.width == LayoutParams.MATCH_PARENT){
            HuaBanWidth = MeasureSpec.getSize(widthMeasureSpec).toFloat();
        }
        if (layoutParams.height == LayoutParams.WRAP_CONTENT ||layoutParams.height == LayoutParams.MATCH_PARENT){

            val makeMeasureSpec =
                MeasureSpec.makeMeasureSpec(textSize.toInt(), MeasureSpec.AT_MOST);
            HuabanHeight = MeasureSpec.getSize(makeMeasureSpec).toFloat();
        }


        val makeMeasureWidthSpec =
            MeasureSpec.makeMeasureSpec(HuaBanWidth.toInt(), MeasureSpec.UNSPECIFIED)
        val makeMeasureHeightSpec =
            MeasureSpec.makeMeasureSpec(HuabanHeight.toInt()+100, MeasureSpec.AT_MOST)
        setMeasuredDimension(MeasureSpec.getSize(makeMeasureWidthSpec) , MeasureSpec.getSize(makeMeasureHeightSpec));
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        var inc = 0f ;
        var i = 0
        this.data.forEach {
            Log.e(TAG, "size: "+MeasureText(data[i] , textSize) )
            if (selectText == it){
                canvas.drawText(it , (LeftFromeRightDistance* (i+1) + inc) , ((measuredHeight + textSize)  / 2 ).toFloat() , selectTextPaint)
                val bgRectF = getSelectRectF(
                    (LeftFromeRightDistance * (i + 1) + inc) - LeftFromeRightDistance+offset,
                    (LeftFromeRightDistance * (i + 1) + inc) + MeasureText(
                        it,
                        textSize
                    ) + LeftFromeRightDistance+offset
                )
                drawBackGround(canvas , bgRectF);
                canvas.drawText(it , (LeftFromeRightDistance* (i+1) + inc)+offset , ((measuredHeight + textSize)  / 2 ).toFloat() , selectTextPaint)
            }else{
                canvas.drawText(it , (LeftFromeRightDistance* (i+1) + inc)+offset , ((measuredHeight + textSize)  / 2 ).toFloat() , textPaint)
            }
            if (isStart){
                distances.add((LeftFromeRightDistance* (i+1) + inc))
            }
            inc+=MeasureText(data[i] , textSize);
            i++;
        }


    }

    /**
     * 绘制选中背景
     */
    private fun drawBackGround(canvas: Canvas , rectF: RectF) {
        canvas.drawRoundRect(rectF , selectBackgroundr , selectBackgroundr , selectPaint)
    }

    private fun getSelectRectF(start : Float, end : Float) : RectF {
        var rectf : RectF ;
        rectf = RectF();
        rectf.top  = 10F ;
        rectf.bottom = measuredHeight.toFloat();
        rectf.right = start+20
        rectf.left =end-20;
        return rectf;

    }

    private fun getTextPadding() : Float {
         var  distacne = 0f;
         this.data.forEach{
             distacne+= MeasureText(it , textSize);
        }

        return (measuredWidth - distacne ) / (data.size)
    }



    override fun onTouchEvent(event: MotionEvent): Boolean {

        Log.e(TAG, "onTouchEvent: "+ -distances[data.size-1])




        if (event.action == MotionEvent.ACTION_DOWN){
            OrdX= event.x;
        }else if (event.action == MotionEvent.ACTION_UP){
            val newX = event.x;
            if (newX  - OrdX < 0){

                isStart = false;
                Log.e(TAG, "onTouchEvent: 左 " )
                index = index+1;
                selectText = this.data[index % data.size]
                currentDistance -= distances[index]

                if (currentDistance < -1262.25 && currentDistance >= (-distances[data.size-1]+ MeasureText(data[data.size-1] , textSize)+currentDistance)){
                    var offIndex = index +1;
                    if (offIndex < data.size){
                        offset =-( LeftFromeRightDistance + MeasureText(data[offIndex] , textSize));
                    }
                }


            }
            if (newX  - OrdX > 0){
                isStart = false;
                index = index - 1;
                if (index < 0){
                    index = 0;
                }
                currentDistance += distances[index]
                selectText = this.data[index]
                Log.e(TAG, "onTouchEvent: 右 " )

                Log.e(TAG, "currentDistance: "+currentDistance + " distances[0] " +distances[0] )
                if (currentDistance < -distances[0]){
                    var offIndex = index -1;
                    if (offIndex >0){

                        // TODO 左边滑动偏移算法 需要另外研究
                        offset = ( LeftFromeRightDistance + MeasureText(data[offIndex] , textSize));
                    }
                }


            }
        }

        invalidate()
        return true;
    }

    public fun setData(data: MutableList<String>) {
        this.data = data;

    }
}